<template>
  <div class="user-list">
    <div class="action-bar">
      <div class="search-area">
        <el-input
          v-model="searchForm.username"
          placeholder="搜索用户名"
          style="width: 200px;"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-input
          v-model="searchForm.email"
          placeholder="搜索邮箱"
          style="width: 200px; margin-left: 12px;"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Message /></el-icon>
          </template>
        </el-input>
        
        <el-input
          v-model="searchForm.phone"
          placeholder="搜索手机号"
          style="width: 200px; margin-left: 12px;"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Phone /></el-icon>
          </template>
        </el-input>
        
        <el-select v-model="searchForm.status" placeholder="状态筛选" style="width: 120px; margin-left: 12px;">
          <el-option label="全部" value="" />
          <el-option label="正常" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
        
        <el-button type="primary" @click="handleSearch" style="margin-left: 12px;">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        
        <el-button @click="resetSearch" style="margin-left: 8px;">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </div>
      
      <div class="action-buttons">
        <el-button type="primary" @click="showAddUserDialog">
          <el-icon><Plus /></el-icon>
          添加用户
        </el-button>
        <el-button @click="exportUsers">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>
    
    <el-table :data="users" style="width: 100%" v-loading="loading">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      
      <el-table-column label="用户信息" min-width="200">
        <template #default="{ row }">
          <div class="user-info">
            <el-avatar :size="40" :src="row.avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'" />
            <div class="user-details">
              <div class="username">{{ row.username }}</div>
              <div class="email">{{ row.email }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column prop="phone" label="手机号" width="120" />
      
      <el-table-column prop="type" label="角色" width="100">
        <template #default="{ row }">
          <el-tag :type="getRoleType(row.type)" size="small">
            {{ getRoleLabel(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
            {{ row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="createTime" label="注册时间" width="160">
        <template #default="{ row }">
          {{ formatDateTime(row.createTime) }}
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="text" size="small" @click="editUser(row)">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button type="text" size="small" @click="toggleUserStatus(row)">
            <el-icon><Lock /></el-icon>
            {{ row.status === 1 ? '禁用' : '启用' }}
          </el-button>
          <el-button type="text" size="small" @click="deleteUser(row)">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 添加用户对话框 -->
    <AddUserDialog
      v-model="showAddDialog"
      @success="handleAddUserSuccess"
    />
    
    <!-- 编辑用户对话框 -->
    <EditUserDialog
      v-model="showEditDialog"
      :userData="currentUser"
      @success="handleEditUserSuccess"
    />
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Message, Phone, Refresh, Plus, Download, Edit, Lock, Delete } from '@element-plus/icons-vue'
import AddUserDialog from './AddUserDialog.vue'
import EditUserDialog from './EditUserDialog.vue'
import axios from '@/plugins/axios'
import * as XLSX from 'xlsx'

export default {
  name: 'UserList',
  components: {
    AddUserDialog,
    EditUserDialog,
    Search,
    Message,
    Phone,
    Refresh,
    Plus,
    Download,
    Edit,
    Lock,
    Delete
  },
  setup() {
    const loading = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(20)
    const total = ref(0)
    const showAddDialog = ref(false)
    const showEditDialog = ref(false)
    const currentUser = ref({})
    const users = ref([])
    
    // 搜索表单
    const searchForm = reactive({
      username: '',
      email: '',
      phone: '',
      status: ''
    })
    
    // 获取用户列表
    const fetchUsers = async () => {
      loading.value = true
      try {
        const params = {
          pageNum: currentPage.value,
          pageSize: pageSize.value
        }
        
        // 构建查询条件，移除空值
        const searchData = {}
        Object.keys(searchForm).forEach(key => {
          if (searchForm[key] !== '' && searchForm[key] !== null && searchForm[key] !== undefined) {
            searchData[key] = searchForm[key]
          }
        })
        
        const response = await axios.post('/user/list', searchData, { params })
        
        if (response.data.code === 1) {
          users.value = response.data.data.records || []
          total.value = response.data.data.total || 0
        } else {
          ElMessage.error(response.data.msg || '获取用户列表失败')
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        ElMessage.error('获取用户列表失败，请检查网络连接')
      } finally {
        loading.value = false
      }
    }
    
    // 搜索
    const handleSearch = () => {
      currentPage.value = 1
      fetchUsers()
    }
    
    // 重置搜索
    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      currentPage.value = 1
      fetchUsers()
    }
    
    // 分页大小改变
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
      fetchUsers()
    }
    
    // 当前页改变
    const handleCurrentChange = (page) => {
      currentPage.value = page
      fetchUsers()
    }
    
    const getRoleType = (type) => {
      // 支持整数类型和字符串类型
      if (typeof type === 'number') {
        const types = {
          0: 'danger',  // 超级管理员
          1: 'warning', // 管理员
          2: 'info'     // 普通用户
        }
        return types[type] || 'info'
      } else {
        const types = {
          'super_admin': 'danger',
          'admin': 'warning',
          'user': 'info'
        }
        return types[type] || 'info'
      }
    }
    
    const getRoleLabel = (type) => {
      // 支持整数类型和字符串类型
      if (typeof type === 'number') {
        const labels = {
          0: '超级管理员',
          1: '管理员',
          2: '普通用户'
        }
        return labels[type] || '未知'
      } else {
        const labels = {
          'super_admin': '超级管理员',
          'admin': '管理员',
          'user': '普通用户'
        }
        return labels[type] || '未知'
      }
    }
    
    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return '-'
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }
    
    const showAddUserDialog = () => {
      showAddDialog.value = true
    }
    
    const handleAddUserSuccess = () => {
      ElMessage.success('用户添加成功，列表已刷新')
      fetchUsers()
    }
    
    const handleEditUserSuccess = () => {
      ElMessage.success('用户更新成功，列表已刷新')
      fetchUsers()
    }
    
    const editUser = (user) => {
      currentUser.value = { ...user }
      showEditDialog.value = true
    }
    
    const toggleUserStatus = async (user) => {
      try {
        const newStatus = user.status === 1 ? 0 : 1
        // 调用后端API来更新用户状态
        const response = await axios.post('/user/update', {
          id: user.id,
          status: newStatus
        })
        
        if (response.data.code === 1) {
          // 更新前端状态
          user.status = newStatus
          ElMessage.success(`用户${newStatus === 1 ? '启用' : '禁用'}成功`)
        } else {
          ElMessage.error(response.data.msg || '操作失败')
        }
      } catch (error) {
        console.error('更新用户状态失败:', error)
        ElMessage.error('操作失败，请重试')
      }
    }
    
    const deleteUser = (user) => {
      ElMessageBox.confirm(
        `确定要删除用户 "${user.username}" 吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          // 调用后端API删除用户
          const response = await axios.post(`/user/delete/${user.id}`)
          
          if (response.data.code === 1) {
            // 从前端列表中移除
            const index = users.value.findIndex(u => u.id === user.id)
            if (index !== -1) {
              users.value.splice(index, 1)
              total.value--
            }
            ElMessage.success('用户删除成功')
          } else {
            ElMessage.error(response.data.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除用户失败:', error)
          ElMessage.error('删除失败，请重试')
        }
      })
    }
    
    const exportUsers = async () => {
      try {
        loading.value = true
        ElMessage.info('正在准备导出数据...')
        
        // 获取所有用户数据（不分页）
        const response = await axios.post('/user/list', {}, {
          params: {
            pageNum: 1,
            pageSize: 10000 // 设置一个较大的值以获取所有数据
          }
        })
        
        if (response.data.code !== 1) {
          ElMessage.error(response.data.msg || '获取导出数据失败')
          return
        }
        
        const userData = response.data.data.records || []
        
        if (userData.length === 0) {
          ElMessage.warning('没有可导出的数据')
          return
        }
        
        // 准备Excel数据
        const exportData = userData.map(user => ({
          'ID': user.id,
          '用户名': user.username,
          '账号': user.account,
          '邮箱': user.email || '',
          '手机号': user.phone || '',
          '性别': user.gender === 0 ? '未知' : user.gender === 1 ? '男' : '女',
          '用户类型': getRoleLabel(user.type),
          '状态': user.status === 1 ? '正常' : '禁用',
          '注册时间': formatDateTime(user.createTime)
        }))
        
        // 创建工作簿
        const worksheet = XLSX.utils.json_to_sheet(exportData)
        const workbook = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(workbook, worksheet, '用户列表')
        
        // 设置列宽
        const columnWidths = [
          { wch: 8 },  // ID
          { wch: 15 }, // 用户名
          { wch: 15 }, // 账号
          { wch: 25 }, // 邮箱
          { wch: 15 }, // 手机号
          { wch: 8 },  // 性别
          { wch: 15 }, // 用户类型
          { wch: 8 },  // 状态
          { wch: 20 }  // 注册时间
        ]
        worksheet['!cols'] = columnWidths
        
        // 导出Excel文件
        const now = new Date()
        const timestamp = `${now.getFullYear()}${(now.getMonth()+1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}`
        const fileName = `用户列表_${timestamp}.xlsx`
        
        XLSX.writeFile(workbook, fileName)
        ElMessage.success(`成功导出 ${userData.length} 条用户数据`)
      } catch (error) {
        console.error('导出用户数据失败:', error)
        ElMessage.error('导出失败，请重试')
      } finally {
        loading.value = false
      }
    }
    
    // 组件挂载时获取用户列表
    onMounted(() => {
      fetchUsers()
    })
    
    return {
      loading,
      currentPage,
      pageSize,
      total,
      showAddDialog,
      showEditDialog,
      currentUser,
      users,
      searchForm,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      getRoleType,
      getRoleLabel,
      formatDateTime,
      showAddUserDialog,
      handleAddUserSuccess,
      handleEditUserSuccess,
      editUser,
      toggleUserStatus,
      deleteUser,
      exportUsers
    }
  }
}
</script>

<style scoped>
.user-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.search-area {
  display: flex;
  align-items: center;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.email {
  color: #666;
  font-size: 12px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
